package com.crean.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 鉴权
 */
@Component
public class AuthFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return FilterContents.ORDER_AUTH;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return (boolean) ctx.getOrDefault(FilterContents.FILTER_RESULT, true);
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        // TODO 部分接口不需要校验

        String authJwt = request.getHeader("authorization");
        if (StringUtils.isEmpty(authJwt)) {
            ctx.setSendZuulResponse(false);// 过滤该请求，不对其进行路由
            ctx.setResponseStatusCode(401);// 返回错误码
            ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody("{\"result\":\"authorization info not found!\"}");// 返回错误内容
            ctx.set(FilterContents.FILTER_RESULT, false);
            return null;
        } else {
            // TODO 解析jwt
            ctx.set(FilterContents.FILTER_RESULT, true);
        }

        return null;
    }
}
